// 封装 fetch
import redux from '~/redux/store'

// 使用Get方式请求数据
let get = (url) => {
  return new Promise((resolve, reject) => {
    fetch(url, {
      method: 'GET',
      headers: new Headers(Object.assign({
        'Accept': 'application/json',
        "Content-Type": "application/json",
        "X-Token": getToken(),
      }))
    }).then((response) => {
      if (response.status == 200) {
        return response.json()
      }
    }).then((data) => {
      console.debug("[GET]", url)
      // resolve data
      resolve(data)
    }).catch((error) => {
      reject(error)
    })
  })
}

// 使用post方式请求数据
let post = (url, data={}) => {
  return new Promise((resolve, reject) => {
    fetch(url, {
      method: 'POST',
      body: JSON.stringify(data),
      headers: new Headers(Object.assign({
        'Accept': 'application/json',
        "Content-Type": "application/json",
        "X-Token": getToken(),
      }))
    }).then((response) => {
      if (response.status == 200) {
        resolve(response.json())
      }

      // todo 统一处理状态码 !=200 错误信息
    }).catch((error) => {
      reject(error)
    })
  })
}

// 上传数据, ???
// var formData = new FormData();
// formData.append('username', 'abc123');
// formData.append('avatar', fileField.files[0]);

let upload = (url, formData) => {
  return new  Promise(() => {
    fetch(url, {
      method: 'POST',
      body: FormData,
      headers: new Headers(Object.assign({
        "Content-Type": "application/x-www-form-urlencoded",
        "X-Token": getToken(),
      }))
    }).then((response) => {
      resolve(response.json())
    })
  })
}

// 获取token
let getToken = () => {
  state = redux.getState()
  return state.app.token || null
}

export default {
  get,
  post,
  upload,
}
